Classes and Objects Tutorial




Classes and Objects Tutorial
An Introduction to Classes and Inheritance
Python Inheritance
Introduction to Classes
Python Object Oriented
Python Classes and Objects

Python Classes and Methods

Python is an “object-oriented programming language.” This means that almost all the code is implemented using a special construct called classes. Programmers use classes to keep related things together. This is done using the keyword “class,” which is a grouping of object-oriented constructs. By the end of this tutorial you will be able to: Define what is a class Describe how to create a class Define what is a method Describe how to do object instantiation Describe how to create instance attributes in Python

What is a class?

A class is a code template for creating objects. Objects have member variables and have behaviour associated with them. In python a class is created by the keyword class. An object is created using the constructor of the class. This object will then be called the instance of the class. In Python we create instances in the following manner Instance = class(arguments) e.g. ratsnake = Snake() william = person()

How to create a class

The simplest class can be created using the class keyword. For example, let's create a simple, empty class with no functionalities. >>> class Snake: ... pass ... >>> snake = Snake() >>> print(snake) <__main__.Snake object at 0x7f315c573550>

Attributes and Methods in class:

A class by itself is of no use unless there is some functionality associated with it. Functionalities are defined by setting attributes, which act as containers for data and functions related to those attributes. Those functions are called methods.

Attributes:

You can define the following class with the name Snake. This class will have an attribute name. >>> class Snake: ... name = "python" # set an attribute `name` of the class ... You can assign the class to a variable. This is called object instantiation. You will then be able to access the attributes that are present inside the class using the dot . operator. For example, in the Snake example, you can access the attribute name of the class Snake. >>> # instantiate the class Snake and assign it to variable snake >>> snake = Snake() >>> # access the class attribute name inside the class Snake. >>> print(snake.name) python

Methods

Once there are attributes that “belong” to the class, you can define functions that will access the class attribute. These functions are called methods. When you define methods, you will need to always provide the first argument to the method with a self keyword. For example, you can define a class Snake, which has one attribute name and one method change_name. The method change name will take in an argument new_name along with the keyword self. >>> class Snake: ... name = "python" ... ... def change_name(self, new_name): # note that the first argument is self ... self.name = new_name # access the class attribute with the self keyword ... Now, you can instantiate this class Snake with a variable snake and then change the name with the method change_name. >>> # instantiate the class >>> snake = Snake() >>> # print the current object name >>> print(snake.name) python >>> # change the name using the change_name method >>> snake.change_name("anaconda") >>> print(snake.name) anaconda

Instance attributes in python and the init method

You can also provide the values for the attributes at runtime. This is done by defining the attributes inside the init method. The following example illustrates this. class Snake: def __init__(self, name): self.name = name def change_name(self, new_name): self.name = new_name Now you can directly define separate attribute values for separate objects. For example, >>> # two variables are instantiated >>> python = Snake("python") >>> anaconda = Snake("anaconda") >>> # print the names of the two variables >>> print(python.name) python >>> print(anaconda.name) anaconda

Inheritance and Composition

Classes are written to organize and structure code into meaningful blocks to provide for simpler interfaces which can then be used to build even simpler blocks. There are lots of times when we will need to establish relationships between the classes that we build. These relationships can then be established using either inheritance or composition. In case you are already doing object oriented programming in some other language, you may want to check out our notes on design patterns.

Python inheritance

What is Inheritance

In inheritance an object is based on another object. When inheritance is implemented, the methods and attributes that were defined in the base class will also be present in the inherited class. This is generally done to abstract away similar code in multiple classes. The abstracted code will reside in the base class and the previous classes will now inherit from the base class.

How to achieve Inheritance in Python

Python allows the classes to inherit commonly used attributes and methods from other classes through inheritance. We can define a base class in the following manner: class DerivedClassName(BaseClassName): pass Let's look at an example of inheritance. In the following example, Rocket is the base class and MarsRover is the inherited class. class Rocket: def __init__(self, name, distance): self.name = name self.distance = distance def launch(self): return "%s has reached %s" % (self.name, self.distance) class MarsRover(Rocket): # inheriting from the base class def __init__(self, name, distance, maker): Rocket.__init__(self, name, distance) self.maker = maker def get_maker(self): return "%s Launched by %s" % (self.name, self.maker) if __name__ == "__main__": x = Rocket("simple rocket", "till stratosphere") y = MarsRover("mars_rover", "till Mars", "ISRO") print(x.launch()) print(y.launch()) print(y.get_maker()) The output of the code above is shown below: ➜ Documents python rockets.py simple rocket has reached till stratosphere mars_rover has reached till Mars mars_rover Launched by ISRO

Python Composition:

What is composition

In composition, we do not inherit from the base class but establish relationships between classes through the use of instance variables that are references to other objects. Talking in terms of pseudocode you may say that class GenericClass: define some attributes and methods class ASpecificClass: Instance_variable_of_generic_class = GenericClass # use this instance somewhere in the class some_method(Instance_variable_of_generic_class) So you will instantiate the base class and then use the instance variable for any business logic.

How to achieve composition in Python

To achieve composition you can instantiate other objects in the class and then use those instances. For example in the below example we instantiate the Rocket class using self.rocket and then using self.rocket in the method get_maker. class MarsRoverComp(): def __init__(self, name, distance, maker): self.rocket = Rocket(name, distance) # instantiating the base self.maker = maker def get_maker(self): return "%s Launched by %s" % (self.rocket.name, self.maker) if __name__ == "__main__": z = MarsRover("mars_rover2", "till Mars", "ISRO") print(z.launch()) print(z.get_maker()) The output of the total code which has both inheritance and composition is shown below: ➜ Documents python rockets.py simple rocket has reached till stratosphere mars_rover has reached till Mars mars_rover Launched by ISRO mars_rover2 has reached till Mars mars_rover2 Launched by ISRO

Errors and Exceptions in Python

Errors are problems in the program that the program should not recover from. If at any point in the program an error occurs, then the program should exit gracefully. On the other hand, Exceptions are raised when an external event occurs which in some way changes the normal flow of the program. In this tutorial you will learn about common types of Errors and Exceptions in Python and common paradigms in handling them.

Handling Exceptions with Try/Except/Finally

Errors and Exceptions in Python are handled with the Try: Except: Finally construct. You put the unsafe code in the try: block. You put the fall-back code in the Except: block. The final code is kept in the Finally: block. For example, look at the code below. >>> try: ... print("in the try block") ... print(1/0) ... except: ... print("In the except block") ... finally: ... print("In the finally block") ... in the try block In the except block In the finally block

Raising exceptions for a predefined condition

Exceptions can also be raised if you want the code to behave within specific parameters. For example, if you want to limit the user-input to only positive integers, raise an exception. # exc.py while True: try: user = int(input()) if user < 0: raise ValueError("please give positive number") else: print("user input: %s" % user) except ValueError as e: print(e) So the output of the above program is: ➜ python exc.py 4 user input: 4 3 user input: 3 2 user input: 2 1 user input: 1 -1 please give positive number 5 user input: 5 2 user input: 2 -5 please give positive number ^C Traceback (most recent call last): File "exc.py", line 3, in <module> user = int(input()) KeyboardInterrupt